﻿using System;
using System.Windows;
using SimpleDbBrowser.ViewModel;
using System.Windows.Input;

namespace SimpleDbBrowser.Windows
{
    /// <summary>
    /// Interaction logic for Options.xaml
    /// </summary>
    public partial class OptionsView : Window
    {
        /// <summary>
        /// Initializes a new instance of the OptionsView class.
        /// </summary>
        public OptionsView()
        {
            this.InitializeCommands();
            this.InitializeComponent();
        }

        private void InitializeCommands()
        {
            this.CommitChanges = new RelayCommand(this.ExecuteCommitChanges, this.CanExecuteCommitChanges);
            this.ApplyChanges = new RelayCommand(this.ExecuteApplyChanges, this.CanExecuteCommitChanges);
            this.CancelChanges = new RelayCommand(this.ExecuteCancelChanges);
        }

        /// <summary>
        /// Handles actions that must be performed when the OptionsView is 
        /// closed.
        /// </summary>
        /// <param name="e">
        /// The Closed event arguments.
        /// </param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
        }

        public ICommand ApplyChanges { get; private set; }

        public ICommand CommitChanges { get; private set; }

        public ICommand CancelChanges { get; private set; }

        private void ExecuteCommitChanges(object param)
        {
            if (this.DataContext == null) return;

            var vm = (OptionsViewModel)this.DataContext;
            vm.Commit.Execute(param);
            this.DialogResult = true;
            this.Close();
        }

        private bool CanExecuteCommitChanges(object param)
        {
            if (this.DataContext == null) return false;
            var vm = (OptionsViewModel)this.DataContext;
            return vm.Commit.CanExecute(param);
        }

        private void ExecuteApplyChanges(object param)
        {
            if (this.DataContext == null) return;

            var vm = (OptionsViewModel)this.DataContext;
            vm.Commit.Execute(param);

            return;
        }

        private bool CanExecuteApplyChanges(object param)
        {
            if (this.DataContext == null) return false;

            var vm = (OptionsViewModel)this.DataContext;
            return vm.Commit.CanExecute(param);
        }

        private void ExecuteCancelChanges(object param)
        {
            this.DialogResult = false;
            this.Close();
        }
    }
}
